﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using BitworkStudios.Web.Mvc.Framework.SiteMap.Providers;
using XmlSiteMapProvider = BitworkStudios.Web.Mvc.Framework.SiteMap.Providers.XmlSiteMapProvider;

namespace BitworkStudios.Web.Mvc.Framework.SiteMap
{
    public class DefaultSiteMapProvider : StaticSiteMapProvider
    {
        public ISiteMapProvider SiteMapProvider { get; set; }

        public override SiteMapNode RootNode
        {
            get { return SiteMapProvider.BuildSiteMap(); }
        }

        public override void Initialize(string name, NameValueCollection attributes)
        {
            base.Initialize(name, attributes);
            SiteMapProvider = new XmlSiteMapProvider(name, attributes); 
        }

        protected override void Clear()
        {
            SiteMapProvider.Clear();
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return SiteMapProvider.RootNode;
        }

        public override SiteMapNode BuildSiteMap()
        {
            return SiteMapProvider.BuildSiteMap();
        }

        public override SiteMapNode CurrentNode
        {
            get
            {
                return GetCurrentNode();
            }
        }

        private SiteMapNode GetCurrentNode()
        {
            string currentRequestedPath = HttpContext.Current.Request.Url.AbsolutePath;
            return Descendants(RootNode).First(node => node.Url == currentRequestedPath);
        }

        private IEnumerable<SiteMapNode> Descendants(SiteMapNode root)
        {
            var nodes = new Stack<SiteMapNode>(new[] { root });
            while (nodes.Any())
            {
                SiteMapNode node = nodes.Pop();
                yield return node;
                foreach (SiteMapNode n in node.ChildNodes) nodes.Push(n);
            }
        }
    }
}
